package edu.stanford.cs.cs294s;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class ImageUpload {
	public ImageUpload(){
		
	}
	
	public void uploadImage(String fileName){
		HttpURLConnection connection = null;
		DataOutputStream outputStream = null;
		DataInputStream inputStream = null;

		String pathToOurFile = "/data/file_to_send.mp3";
		String urlServer = "http://colby.stanford.edu/cs294s/location/upload.php";
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary =  "*****";

		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;
		int maxBufferSize = 1*1024*1024;

		try
		{
		//FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
		FileInputStream fileInputStream = new FileInputStream(fileName);

		URL url = new URL(urlServer);
		connection = (HttpURLConnection) url.openConnection();

		// Allow Inputs & Outputs
		connection.setDoInput(true);
		connection.setDoOutput(true);
		connection.setUseCaches(false);

		// Enable POST method
		connection.setRequestMethod("POST");

		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

		outputStream = new DataOutputStream( connection.getOutputStream() );
		outputStream.writeBytes(twoHyphens + boundary + lineEnd);
		String upFile = "newphoto.jpg";
		outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + upFile +"\"" + lineEnd);
		outputStream.writeBytes(lineEnd);

		bytesAvailable = fileInputStream.available();
		bufferSize = Math.min(bytesAvailable, maxBufferSize);
		buffer = new byte[bufferSize];

		// Read file
		bytesRead = fileInputStream.read(buffer, 0, bufferSize);

		while (bytesRead > 0)
		{
		outputStream.write(buffer, 0, bufferSize);
		bytesAvailable = fileInputStream.available();
		bufferSize = Math.min(bytesAvailable, maxBufferSize);
		bytesRead = fileInputStream.read(buffer, 0, bufferSize);
		}

		outputStream.writeBytes(lineEnd);
		outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

		// Responses from the server (code and message)
		int serverResponseCode = connection.getResponseCode();
		String serverResponseMessage = connection.getResponseMessage();
		System.err.println("Server Response code : " + serverResponseCode + 
				" message : " + serverResponseMessage);

		fileInputStream.close();
		outputStream.flush();
		
		BufferedReader b = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String msg = "";
		String m;
		while((m = b.readLine())!=null){
			 msg += m;
		}
		System.err.println("Response : " + msg);
		
		b.close();
		outputStream.close();
		}
		catch (Exception ex)
		{
		//Exception handling
		}
	}
	
	
	void uploadImage2(String filename){
		boolean success;
		try {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			File f = new File(filename);

			HttpPost httpost = new HttpPost("http://colby.stanford.edu/cs294s/location/upload.php");
			MultipartEntity entity = new MultipartEntity();
			entity.addPart("uploadedfile", new StringBody("newphoto.jpg"));
			entity.addPart("myFile", new FileBody(f));
			httpost.setEntity(entity);

			HttpResponse response;
							
			response = httpclient.execute(httpost);

			Log.d("httpPost", "Login form get: " + response.getStatusLine());

			if (entity != null) {
				entity.consumeContent();
			}
			success = true;
		} catch (Exception ex) {
			Log.d("FormReviewer", "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace());
			success = false;
		} finally {
			//mDebugHandler.post(mFinishUpload);
		}
	}
	
	void upload3(byte[] data){
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost("http://colby.stanford.edu/cs294s/location/upload.php");
		//HttpPost httppost = new HttpPost("http://beyondanalog.com/picupload/upload.php");
		ByteArrayEntity entity = new ByteArrayEntity(data);
		try { 
			System.err.println("File Size : " + data.length);
			httppost.addHeader("uploadedfile", "newphoto.jpg");
            // Construct data 
			httppost.setEntity(entity);
			HttpResponse response = httpclient.execute(httppost);
			System.err.println("RESPONSE : " + GetText(response.getEntity().getContent()));
            
        } catch (Exception e) {
        	e.printStackTrace();
        }
	}
	
	public static String GetText(InputStream in)
	{
		String text = "";
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try
		{
			while((line = reader.readLine()) != null)
			{
				sb.append(line + "\n");
			}
			text = sb.toString();
		}
		catch(Exception ex)
		{
		
		}
		finally
		{
			try
			{
		
				in.close();
			}
			catch(Exception ex) {}
		}
		return text;
	}
}
